package com.apes.fn.fico.reimbursement.service;

import com.apes.fn.fico.reimbursement.model.FeeTypeExpense;
import com.apes.fn.fico.reimbursement.repository.FeeTypeExpenseRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author cyy
 */
@Service("feeTypeExpenseService")
public class FeeTypeExpenseService extends DomainService{

    @Autowired
    private FeeTypeExpenseRepository feeTypeExpenseRepository;


    public FeeTypeExpense save(SimpleRequest request){
        FeeTypeExpense feeTypeExpense = request.getO(FeeTypeExpense.class);
        return feeTypeExpenseRepository.saveAndFlush(feeTypeExpense);
    }

    public FeeTypeExpense update(SimpleRequest request) {
        FeeTypeExpense feeTypeExpense = request.getO(FeeTypeExpense.class);
        feeTypeExpense.setUpdateDate(new Date());
        return feeTypeExpenseRepository.saveAndFlush(feeTypeExpense);
    }

    public FeeTypeExpense approve(SimpleRequest request) {
        FeeTypeExpense feeTypeExpense = request.getO(FeeTypeExpense.class);
        feeTypeExpense.setApproveDate(new Date());
        feeTypeExpense.setApproveId(request.getPerson());
        feeTypeExpense.setState("approve");
        return feeTypeExpenseRepository.saveAndFlush(feeTypeExpense);
    }

    public String delete(SimpleRequest request){
        checkData(request);
        FeeTypeExpense feeTypeExpense = request.getO(FeeTypeExpense.class);
        feeTypeExpenseRepository.delete(feeTypeExpense);
        return "删除成功";
    }

    public void checkData(SimpleRequest request) {
        String id = request.get("id");
        int version = request.get("version");
        // 从数据库中取数，检查数据
        FeeTypeExpense feeTypeExpense = feeTypeExpenseRepository.findOne(id);
        if (feeTypeExpense == null) throw new RuntimeException("费用单【" + id + "】在系统中不存在。");
        if (feeTypeExpense.getVersion() != version) throw new RuntimeException("记录已更新或已删除，请重新提交！");
    }
}
